<script setup>
import { ref, onBeforeUnmount, watch, computed } from "vue";
import {
  Gauge,
  Clock,
  Trophy,
  Star,
  Zap,
  CheckCircle,
  XCircle,
} from "lucide-vue-next";
const { t } = useI18n();
const SYMBOLS = ["◆", "★", "▲", "●", "■", "◇", "☆", "△", "○", "□"];
const SYMBOL_DIGIT_MAP = {
  "◆": 1,
  "★": 2,
  "▲": 3,
  "●": 4,
  "■": 5,
  "◇": 6,
  "☆": 7,
  "△": 8,
  "○": 9,
  "□": 0,
};
const LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const NUMBERS = "0123456789";
const TOTAL_TASKS = 90;

const emit = defineEmits(["complete"]);

const stage = ref("instructions");
const currentTaskIndex = ref(0);
const tasks = ref([]);
const responses = ref([]);
const reactionTimes = ref([]);
const accuracy = ref([]);
const timeLeft = ref(240);
const startTime = ref(0);
const taskStartTime = ref(0);
const score = ref(0);
const correctStreak = ref(0);
const maxStreak = ref(0);
const feedback = ref({ show: false, correct: false, reactionTime: 0 });
const awaitingResponse = ref(true);

let timerInterval = null;
let feedbackTimeout = null;

const task = computed(() => tasks.value[currentTaskIndex.value]);

const generateSymbolDigitTask = () => {
  const symbol = SYMBOLS[Math.floor(Math.random() * SYMBOLS.length)];
  const correctDigit = SYMBOL_DIGIT_MAP[symbol];
  const options = [correctDigit];
  while (options.length < 4) {
    const option = Math.floor(Math.random() * 10);
    if (!options.includes(option)) options.push(option);
  }
  for (let i = options.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [options[i], options[j]] = [options[j], options[i]];
  }
  return { symbol, options, correctDigit };
};

const generateVisualSearchTask = () => {
  const target = LETTERS[Math.floor(Math.random() * LETTERS.length)];
  const distractorCount = Math.floor(Math.random() * 8) + 12;
  const targetPresent = Math.random() < 0.5;
  const distractors = [];
  for (let i = 0; i < distractorCount; i++) {
    let distractor;
    do {
      distractor = LETTERS[Math.floor(Math.random() * LETTERS.length)];
    } while (distractor === target);
    distractors.push(distractor);
  }
  if (targetPresent) {
    const insertIndex = Math.floor(Math.random() * (distractors.length + 1));
    distractors.splice(insertIndex, 0, target);
  }
  return { target, distractors, targetPresent };
};

const generateComparisonTask = () => {
  const length = Math.floor(Math.random() * 3) + 3;
  const item1 = Array.from({ length }, () =>
    Math.random() < 0.5
      ? LETTERS[Math.floor(Math.random() * LETTERS.length)]
      : NUMBERS[Math.floor(Math.random() * NUMBERS.length)]
  ).join("");
  const same = Math.random() < 0.5;
  let item2 = item1;
  if (!same) {
    const changeCount = Math.floor(Math.random() * 2) + 1;
    const chars = item2.split("");
    for (let i = 0; i < changeCount; i++) {
      const index = Math.floor(Math.random() * chars.length);
      chars[index] = /[A-Z]/.test(chars[index])
        ? LETTERS[Math.floor(Math.random() * LETTERS.length)]
        : NUMBERS[Math.floor(Math.random() * NUMBERS.length)];
    }
    item2 = chars.join("");
  }
  return { item1, item2, same };
};

const generateTasks = () => {
  const newTasks = [];
  const taskTypes = ["symbol-digit", "visual-search", "simple-comparison"];
  for (let i = 0; i < TOTAL_TASKS; i++) {
    const type = taskTypes[i % taskTypes.length];
    let content, correctAnswer;
    switch (type) {
      case "symbol-digit":
        content = generateSymbolDigitTask();
        correctAnswer = content.correctDigit;
        break;
      case "visual-search":
        content = generateVisualSearchTask();
        correctAnswer = content.targetPresent;
        break;
      case "simple-comparison":
        content = generateComparisonTask();
        correctAnswer = content.same;
        break;
    }
    newTasks.push({ id: i + 1, type, content, correctAnswer });
  }
  return newTasks;
};

const handleStartTest = () => {
  stage.value = "test";
  startTime.value = Date.now();
};

const handleResponse = (response) => {
  if (!awaitingResponse.value) return;

  const reactionTime = Date.now() - taskStartTime.value;
  if (!task.value) return;

  const correct = response === task.value.correctAnswer;

  awaitingResponse.value = false;
  responses.value.push(response);
  reactionTimes.value.push(reactionTime);
  accuracy.value.push(correct);

  feedback.value = { show: true, correct, reactionTime };

  if (correct) {
    score.value++;
    const newStreak = correctStreak.value + 1;
    correctStreak.value = newStreak;
    maxStreak.value = Math.max(maxStreak.value, newStreak);
  } else {
    correctStreak.value = 0;
  }

  feedbackTimeout = setTimeout(() => {
    feedback.value = { show: false, correct: false, reactionTime: 0 };
    awaitingResponse.value = true;
    if (currentTaskIndex.value < tasks.value.length - 1) {
      currentTaskIndex.value++;
    } else {
      stage.value = "results";
    }
  }, 1000);
};

const handleComplete = () => {
  if (!accuracy.value.length || !reactionTimes.value.length) return;

  const totalCorrect = accuracy.value.filter((a) => a).length;
  const overallAccuracy =
    accuracy.value.length > 0
      ? Math.round((totalCorrect / accuracy.value.length) * 100)
      : 0;
  const averageRT =
    reactionTimes.value.length > 0
      ? Math.round(
          reactionTimes.value.reduce((sum, rt) => sum + rt, 0) /
            reactionTimes.value.length
        )
      : 0;
  const timeUsedMinutes = (Date.now() - startTime.value) / 60000;
  const correctPerMinute =
    timeUsedMinutes > 0 ? Math.round(totalCorrect / timeUsedMinutes) : 0;

  let finalScore = 0;
  finalScore += overallAccuracy * 0.5;
  const speedScore = Math.min(100, correctPerMinute * 2);
  finalScore += speedScore * 0.3;
  const rtVariance =
    reactionTimes.value.length > 1
      ? reactionTimes.value.reduce(
          (sum, rt) => sum + Math.pow(rt - averageRT, 2),
          0
        ) / reactionTimes.value.length
      : 0;
  const consistencyScore = Math.max(0, 100 - Math.sqrt(rtVariance) / 50);
  finalScore += consistencyScore * 0.15;
  const streakBonus =
    totalCorrect > 0
      ? Math.min(100, (maxStreak.value / totalCorrect) * 100)
      : 0;
  finalScore += streakBonus * 0.05;
  finalScore = Math.round(Math.max(0, Math.min(100, finalScore)));

  const timeUsed = Math.round((Date.now() - startTime.value) / 1000);

  const symbolDigitTasks = tasks.value.filter(
    (t) => t && t.type === "symbol-digit"
  ).length;
  const symbolDigitCorrect = accuracy.value.filter(
    (a, i) => tasks.value[i] && tasks.value[i].type === "symbol-digit" && a
  ).length;
  const symbolDigitAccuracy =
    symbolDigitTasks > 0
      ? Math.round((symbolDigitCorrect / symbolDigitTasks) * 100)
      : 0;

  const visualSearchTasks = tasks.value.filter(
    (t) => t && t.type === "visual-search"
  ).length;
  const visualSearchCorrect = accuracy.value.filter(
    (a, i) => tasks.value[i] && tasks.value[i].type === "visual-search" && a
  ).length;
  const visualSearchAccuracy =
    visualSearchTasks > 0
      ? Math.round((visualSearchCorrect / visualSearchTasks) * 100)
      : 0;

  const comparisonTasks = tasks.value.filter(
    (t) => t && t.type === "simple-comparison"
  ).length;
  const comparisonCorrect = accuracy.value.filter(
    (a, i) => tasks.value[i] && tasks.value[i].type === "simple-comparison" && a
  ).length;
  const comparisonAccuracy =
    comparisonTasks > 0
      ? Math.round((comparisonCorrect / comparisonTasks) * 100)
      : 0;

  const result = {
    id: Date.now().toString(),
    testType: "processing-speed",
    score: finalScore,
    completedAt: new Date(),
    duration: timeUsed,
    details: {
      totalTasks: tasks.value.length,
      correctResponses: totalCorrect,
      overallAccuracy,
      averageReactionTime: averageRT,
      correctPerMinute,
      maxStreakLength: maxStreak.value,
      symbolDigitAccuracy,
      visualSearchAccuracy,
      comparisonAccuracy,
      processingSpeedIndex: correctPerMinute,
      consistencyScore: Math.round(consistencyScore),
      speedScore: Math.round(speedScore),
      streakBonus: Math.round(streakBonus),
    },
  };
  emit("complete", result);
};

watch(stage, (newStage) => {
  if (newStage === "test") {
    tasks.value = generateTasks();
    taskStartTime.value = Date.now();
    timerInterval = setInterval(() => {
      if (timeLeft.value <= 1) {
        stage.value = "results";
      } else {
        timeLeft.value--;
      }
    }, 1000);
  } else {
    clearInterval(timerInterval);
  }
});

watch(currentTaskIndex, () => {
  if (stage.value === "test") {
    taskStartTime.value = Date.now();
  }
});

onBeforeUnmount(() => {
  clearInterval(timerInterval);
  clearTimeout(feedbackTimeout);
});

const progress = computed(() => (currentTaskIndex.value / TOTAL_TASKS) * 100);

const finalResult = computed(() => {
  if (stage.value !== "results" || !accuracy.value.length) return {};
  const totalCorrect = accuracy.value.filter((a) => a).length;
  const overallAccuracy = Math.round(
    (totalCorrect / accuracy.value.length) * 100
  );
  const averageRT = Math.round(
    reactionTimes.value.reduce((sum, rt) => sum + rt, 0) /
      reactionTimes.value.length
  );
  const timeUsedMinutes = (Date.now() - startTime.value) / 60000;
  const correctPerMinute =
    timeUsedMinutes > 0 ? Math.round(totalCorrect / timeUsedMinutes) : 0;
  const rtVariance =
    reactionTimes.value.length > 1
      ? reactionTimes.value.reduce(
          (sum, rt) => sum + Math.pow(rt - averageRT, 2),
          0
        ) / reactionTimes.value.length
      : 0;
  const consistencyScore = Math.max(0, 100 - Math.sqrt(rtVariance) / 50);
  let finalScore = 0;
  finalScore += overallAccuracy * 0.5;
  const speedScore = Math.min(100, correctPerMinute * 2);
  finalScore += speedScore * 0.3;
  finalScore += consistencyScore * 0.15;
  const streakBonus =
    totalCorrect > 0
      ? Math.min(100, (maxStreak.value / totalCorrect) * 100)
      : 0;
  finalScore += streakBonus * 0.05;
  finalScore = Math.round(Math.max(0, Math.min(100, finalScore)));

  return {
    finalScore,
    correctPerMinute,
    averageRT,
    overallAccuracy,
    maxStreak: maxStreak.value,
    totalCorrect,
    tasksCount: tasks.value.length,
    speedScore,
    consistencyScore,
    streakBonus,
  };
});
</script>

<template>
  <div v-if="stage === 'instructions'" class="max-w-2xl mx-auto">
    <Card class="bg-white/90 backdrop-blur-sm border-amber-200 shadow-lg">
      <CardHeader class="text-center pb-8">
        <div
          class="w-16 h-16 bg-gradient-to-br from-amber-600 to-orange-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
        >
          <Gauge class="w-8 h-8 text-white" />
        </div>
        <CardTitle class="text-2xl text-slate-800">{{
          t("processingSpeedTest.title")
        }}</CardTitle>
        <p class="text-slate-600 mt-2">
          {{ t("processingSpeedTest.description") }}
        </p>
      </CardHeader>
      <CardContent class="space-y-6">
        <div
          class="bg-gradient-to-r from-amber-50 to-orange-50 rounded-xl p-6 border border-amber-100"
        >
          <h3 class="font-semibold text-amber-900 mb-4 flex items-center gap-2">
            <Star class="w-5 h-5" />
            {{ t("processingSpeedTest.instructionsTitle") }}
          </h3>
          <div class="space-y-3 text-slate-700">
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-amber-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >1</span
              >
              <p>
                <strong>{{ t("processingSpeedTest.taskSymbolDigit") }}</strong
                >：{{ t("processingSpeedTest.taskSymbolDigitDesc") }}
              </p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-amber-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >2</span
              >
              <p>
                <strong>{{ t("processingSpeedTest.taskVisualSearch") }}</strong
                >：{{ t("processingSpeedTest.taskVisualSearchDesc") }}
              </p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-amber-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >3</span
              >
              <p>
                <strong>{{
                  t("processingSpeedTest.taskSimpleComparison")
                }}</strong
                >：{{ t("processingSpeedTest.taskSimpleComparisonDesc") }}
              </p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-amber-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >4</span
              >
              <p>{{ t("processingSpeedTest.feedbackInfo") }}</p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-amber-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >5</span
              >
              <p>{{ t("processingSpeedTest.goal") }}</p>
            </div>
          </div>
        </div>
        <div class="bg-slate-50 rounded-xl p-4 border border-slate-200">
          <h4 class="font-semibold text-slate-700 mb-3 text-center">
            {{ t("processingSpeedTest.symbolDigitMapTitle") }}
          </h4>
          <div class="grid grid-cols-5 gap-2 text-center">
            <div
              v-for="symbol in SYMBOLS"
              :key="symbol"
              class="flex flex-col items-center gap-1"
            >
              <div class="text-2xl">{{ symbol }}</div>
              <div class="text-lg font-semibold text-slate-600">
                {{ SYMBOL_DIGIT_MAP[symbol] }}
              </div>
            </div>
          </div>
        </div>
        <div class="grid md:grid-cols-3 gap-4">
          <div
            class="text-center p-4 bg-gradient-to-br from-amber-50 to-amber-100 rounded-xl border border-amber-200"
          >
            <div class="text-2xl font-bold text-amber-600 mb-1">
              {{ TOTAL_TASKS }}
            </div>
            <div class="text-sm text-amber-700">
              {{ t("processingSpeedTest.numTasks") }}
            </div>
          </div>
          <div
            class="text-center p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl border border-orange-200"
          >
            <div class="text-2xl font-bold text-orange-600 mb-1">
              {{ timeLeft / 60 }}
            </div>
            <div class="text-sm text-orange-700">
              {{ t("processingSpeedTest.timeLimit") }}
            </div>
          </div>
          <div
            class="text-center p-4 bg-gradient-to-br from-amber-50 to-orange-50 rounded-xl border border-amber-200"
          >
            <div class="text-2xl font-bold text-slate-600 mb-1">3</div>
            <div class="text-sm text-slate-700">
              {{ t("processingSpeedTest.taskTypes") }}
            </div>
          </div>
        </div>
        <Button
          class="w-full bg-gradient-to-r from-amber-600 to-orange-500 hover:from-amber-700 hover:to-orange-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
          size="lg"
          @click="handleStartTest"
          >{{ t("processingSpeedTest.startTest") }}
        </Button>
      </CardContent>
    </Card>
  </div>

  <div v-else-if="stage === 'test' && task" class="max-w-4xl mx-auto space-y-6">
    <div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
      <div class="flex items-center gap-4">
        <Badge
          class="bg-amber-100 text-amber-700 border-amber-300"
          variant="outline"
          >{{ t("processingSpeedTest.task") }} {{ currentTaskIndex + 1 }} /
          {{ tasks.length }}
        </Badge>
        <Badge
          :class="{
            'bg-blue-100 text-blue-700 border-blue-300':
              task.type === 'symbol-digit',
            'bg-green-100 text-green-700 border-green-300':
              task.type === 'visual-search',
            'bg-purple-100 text-purple-700 border-purple-300':
              task.type === 'simple-comparison',
          }"
          variant="outline"
        >
          {{
            task.type === "symbol-digit"
              ? t("processingSpeedTest.taskSymbolDigit")
              : task.type === "visual-search"
              ? t("processingSpeedTest.taskVisualSearch")
              : t("processingSpeedTest.taskSimpleComparison")
          }}
        </Badge>
        <div class="flex items-center gap-2 text-slate-600">
          <Trophy class="w-4 h-4" />
          <span class="font-semibold">{{ score }}</span>
        </div>
        <div
          v-if="correctStreak >= 5"
          class="flex items-center gap-2 text-orange-600"
        >
          <Zap class="w-4 h-4" />
          <span class="font-semibold"
            >{{ t("processingSpeedTest.streak") }}: {{ correctStreak }}</span
          >
        </div>
      </div>
      <div class="flex items-center gap-2">
        <Clock class="w-4 h-4 text-slate-500" />
        <span
          :class="[
            'font-mono text-lg font-bold',
            timeLeft <= 60 ? 'text-red-500' : 'text-slate-700',
          ]"
          >{{ Math.floor(timeLeft / 60) }}:{{
            (timeLeft % 60).toString().padStart(2, "0")
          }}</span
        >
      </div>
    </div>
    <Progress :model-value="progress" class="h-2" />
    <Card class="bg-white/90 backdrop-blur-sm border-amber-200 shadow-lg">
      <CardContent class="py-8 min-h-[24rem] flex items-center justify-center">
        <Transition mode="out-in" name="fade">
          <div :key="currentTaskIndex" class="w-full">
            <div
              v-if="task.type === 'symbol-digit'"
              class="text-center space-y-6 relative"
            >
              <h3 class="text-lg font-semibold text-slate-700 mb-4">
                {{ t("processingSpeedTest.findDigit") }}
              </h3>
              <div
                class="text-8xl font-bold text-slate-800 mb-6 relative mx-auto w-32 h-32 flex items-center justify-center"
              >
                {{ task.content.symbol }}
                <Transition name="pop">
                  <div
                    v-if="feedback.show"
                    :class="[
                      'absolute -top-4 -right-4 w-16 h-16 rounded-full flex items-center justify-center shadow-lg',
                      feedback.correct ? 'bg-green-500' : 'bg-red-500',
                    ]"
                  >
                    <CheckCircle
                      v-if="feedback.correct"
                      class="w-8 h-8 text-white"
                    />
                    <XCircle v-else class="w-8 h-8 text-white" />
                  </div>
                </Transition>
              </div>
              <Transition name="fade">
                <div
                  v-if="feedback.show"
                  class="absolute top-full left-1/2 transform -translate-x-1/2 mt-4"
                >
                  <Badge class="bg-white/90 text-slate-600" variant="outline"
                    >{{ feedback.reactionTime }}ms</Badge
                  >
                </div>
              </Transition>
              <Transition name="fade">
                <div
                  v-if="!feedback.show && awaitingResponse"
                  class="grid grid-cols-2 sm:grid-cols-4 gap-4"
                >
                  <Button
                    v-for="(option, index) in task.content.options"
                    :key="index"
                    class="h-16 text-2xl font-bold bg-white hover:bg-blue-50 text-slate-800 border-2 border-slate-300 hover:border-blue-400 transition-all duration-200"
                    variant="outline"
                    @click="() => handleResponse(option)"
                    >{{ option }}
                  </Button>
                </div>
              </Transition>
            </div>
            <div
              v-else-if="task.type === 'visual-search'"
              class="text-center space-y-6 relative"
            >
              <h3 class="text-lg font-semibold text-slate-700">
                {{ t("processingSpeedTest.findLetter") }}
              </h3>
              <div class="text-4xl font-bold text-blue-600 mb-4">
                {{ t("processingSpeedTest.target") }}:
                {{ task.content.target }}
              </div>
              <div
                class="grid grid-cols-5 sm:grid-cols-7 gap-2 max-w-2xl mx-auto mb-6 relative"
              >
                <div
                  v-for="(letter, index) in task.content.distractors"
                  :key="index"
                  :class="[
                    'w-10 h-10 flex items-center justify-center text-lg font-semibold border rounded',
                    letter === task.content.target
                      ? 'bg-blue-100 border-blue-400 text-blue-800'
                      : 'bg-slate-50 border-slate-300 text-slate-700',
                  ]"
                >
                  {{ letter }}
                </div>
                <Transition name="pop">
                  <div
                    v-if="feedback.show"
                    :class="[
                      'absolute -top-4 -right-4 w-12 h-12 rounded-full flex items-center justify-center shadow-lg',
                      feedback.correct ? 'bg-green-500' : 'bg-red-500',
                    ]"
                  >
                    <CheckCircle
                      v-if="feedback.correct"
                      class="w-6 h-6 text-white"
                    />
                    <XCircle v-else class="w-6 h-6 text-white" />
                  </div>
                </Transition>
              </div>
              <Transition name="fade">
                <div v-if="feedback.show" class="mb-6">
                  <Badge class="bg-white/90 text-slate-600" variant="outline"
                    >{{ feedback.reactionTime }}ms</Badge
                  >
                </div>
              </Transition>
              <Transition name="fade">
                <div
                  v-if="!feedback.show && awaitingResponse"
                  class="flex justify-center gap-4"
                >
                  <Button
                    class="bg-green-500 hover:bg-green-600 text-white px-8 py-3 font-semibold transition-all duration-200"
                    @click="() => handleResponse(true)"
                  >
                    {{ t("processingSpeedTest.exists") }}
                  </Button>
                  <Button
                    class="bg-red-500 hover:bg-red-600 text-white px-8 py-3 font-semibold transition-all duration-200"
                    @click="() => handleResponse(false)"
                  >
                    {{ t("processingSpeedTest.notExists") }}
                  </Button>
                </div>
              </Transition>
            </div>
            <div
              v-else-if="task.type === 'simple-comparison'"
              class="text-center space-y-6 relative"
            >
              <h3 class="text-lg font-semibold text-slate-700 mb-4">
                {{ t("processingSpeedTest.compareStrings") }}
              </h3>
              <div class="space-y-4 relative">
                <div
                  class="text-4xl font-mono font-bold text-slate-800 bg-slate-100 px-6 py-3 rounded-lg"
                >
                  {{ task.content.item1 }}
                </div>
                <div class="text-2xl text-slate-500">vs</div>
                <div
                  class="text-4xl font-mono font-bold text-slate-800 bg-slate-100 px-6 py-3 rounded-lg"
                >
                  {{ task.content.item2 }}
                </div>
                <Transition name="pop">
                  <div
                    v-if="feedback.show"
                    :class="[
                      'absolute top-1/2 -right-4 w-12 h-12 rounded-full flex items-center justify-center shadow-lg transform -translate-y-1/2',
                      feedback.correct ? 'bg-green-500' : 'bg-red-500',
                    ]"
                  >
                    <CheckCircle
                      v-if="feedback.correct"
                      class="w-6 h-6 text-white"
                    />
                    <XCircle v-else class="w-6 h-6 text-white" />
                  </div>
                </Transition>
              </div>
              <Transition name="fade">
                <div v-if="feedback.show" class="mt-4">
                  <Badge class="bg-white/90 text-slate-600" variant="outline"
                    >{{ feedback.reactionTime }}ms</Badge
                  >
                </div>
              </Transition>
              <Transition name="fade">
                <div
                  v-if="!feedback.show && awaitingResponse"
                  class="flex justify-center gap-4 mt-8"
                >
                  <Button
                    class="bg-green-500 hover:bg-green-600 text-white px-8 py-3 font-semibold transition-all duration-200"
                    @click="() => handleResponse(true)"
                  >
                    {{ t("processingSpeedTest.same") }}
                  </Button>
                  <Button
                    class="bg-red-500 hover:bg-red-600 text-white px-8 py-3 font-semibold transition-all duration-200"
                    @click="() => handleResponse(false)"
                  >
                    {{ t("processingSpeedTest.different") }}
                  </Button>
                </div>
              </Transition>
            </div>
          </div>
        </Transition>
      </CardContent>
    </Card>
  </div>

  <div v-else-if="stage === 'results'" class="max-w-2xl mx-auto">
    <div v-if="!accuracy.length" class="text-center p-8">
      <p class="text-slate-600">
        {{ t("processingSpeedTest.calculating") }}
      </p>
    </div>
    <Card
      v-else
      class="bg-white/90 backdrop-blur-sm border-amber-200 shadow-xl"
    >
      <CardHeader class="text-center pb-6">
        <div
          class="w-20 h-20 bg-gradient-to-br from-amber-600 to-orange-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
        >
          <Trophy class="w-10 h-10 text-white" />
        </div>
        <CardTitle class="text-3xl text-slate-800 mb-2">{{
          t("processingSpeedTest.testComplete")
        }}</CardTitle>
        <div
          class="text-6xl font-bold bg-gradient-to-r from-amber-600 to-orange-500 bg-clip-text text-transparent"
        >
          {{ finalResult.finalScore }}
        </div>
        <p class="text-slate-600">{{ t("processingSpeedTest.scoreTitle") }}</p>
      </CardHeader>
      <CardContent class="space-y-6">
        <div class="grid grid-cols-2 gap-4">
          <div
            class="text-center p-4 bg-gradient-to-br from-amber-50 to-amber-100 rounded-xl border border-amber-200"
          >
            <div class="text-2xl font-bold text-amber-600 mb-1">
              {{ finalResult.correctPerMinute }}
            </div>
            <div class="text-sm text-amber-700">
              {{ t("processingSpeedTest.correctPerMinute") }}
            </div>
          </div>
          <div
            class="text-center p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl border border-orange-200"
          >
            <div class="text-2xl font-bold text-orange-600 mb-1">
              {{ finalResult.averageRT }}ms
            </div>
            <div class="text-sm text-orange-700">
              {{ t("processingSpeedTest.avgReactionTime") }}
            </div>
          </div>
        </div>
        <div class="space-y-3">
          <div
            class="flex justify-between items-center p-3 bg-slate-50 rounded-lg"
          >
            <span class="text-slate-600">{{
              t("processingSpeedTest.overallAccuracy")
            }}</span
            ><span class="font-semibold text-slate-800"
              >{{ finalResult.overallAccuracy }}%</span
            >
          </div>
          <div
            class="flex justify-between items-center p-3 bg-slate-50 rounded-lg"
          >
            <span class="text-slate-600">{{
              t("processingSpeedTest.longestStreak")
            }}</span
            ><span class="font-semibold text-slate-800"
              >{{ finalResult.maxStreak
              }}{{ t("processingSpeedTest.times") }}</span
            >
          </div>
          <div
            class="flex justify-between items-center p-3 bg-slate-50 rounded-lg"
          >
            <span class="text-slate-600">{{
              t("processingSpeedTest.tasksCompleted")
            }}</span
            ><span class="font-semibold text-slate-800"
              >{{ finalResult.totalCorrect }}/{{ finalResult.tasksCount }}</span
            >
          </div>
          <div
            class="flex justify-between items-center p-3 bg-slate-50 rounded-lg"
          >
            <span class="text-slate-600">{{
              t("processingSpeedTest.processingSpeedIndex")
            }}</span
            ><span class="font-semibold text-slate-800">{{
              Math.round(finalResult.speedScore)
            }}</span>
          </div>
        </div>
        <div
          class="bg-gradient-to-r from-amber-50 to-orange-50 rounded-xl p-4 border border-amber-100"
        >
          <h3 class="font-semibold text-amber-900 mb-3 flex items-center gap-2">
            <Gauge class="w-5 h-5" />
            {{ t("processingSpeedTest.scoringDetails") }}
          </h3>
          <div class="space-y-2 text-sm">
            <div class="flex justify-between">
              <span class="text-slate-600">{{
                t("processingSpeedTest.accuracyScore")
              }}</span
              ><span class="text-amber-600"
                >+{{ Math.round(finalResult.overallAccuracy * 0.5)
                }}{{ t("processingSpeedTest.points") }}</span
              >
            </div>
            <div class="flex justify-between">
              <span class="text-slate-600">{{
                t("processingSpeedTest.processingSpeedScore")
              }}</span
              ><span class="text-orange-600"
                >+{{ Math.round(finalResult.speedScore * 0.3)
                }}{{ t("processingSpeedTest.points") }}</span
              >
            </div>
            <div class="flex justify-between">
              <span class="text-slate-600">{{
                t("processingSpeedTest.consistencyScore")
              }}</span
              ><span class="text-blue-600"
                >+{{ Math.round(finalResult.consistencyScore * 0.15)
                }}{{ t("processingSpeedTest.points") }}</span
              >
            </div>
            <div class="flex justify-between">
              <span class="text-slate-600">{{
                t("processingSpeedTest.streakBonus")
              }}</span
              ><span class="text-green-600"
                >+{{ Math.round(finalResult.streakBonus * 0.05)
                }}{{ t("processingSpeedTest.points") }}</span
              >
            </div>
          </div>
        </div>
        <Button
          class="w-full bg-gradient-to-r from-amber-600 to-orange-500 hover:from-amber-700 hover:to-orange-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
          size="lg"
          @click="handleComplete"
          >{{ t("processingSpeedTest.viewDetailedResults") }}
        </Button>
      </CardContent>
    </Card>
  </div>
</template>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.pop-enter-active {
  transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275),
    opacity 0.3s ease;
}

.pop-leave-active {
  transition: opacity 0.3s ease;
}

.pop-enter-from,
.pop-leave-to {
  transform: scale(0);
  opacity: 0;
}
</style>
